var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var check = require('../../../utils/check.js');

var app = getApp();
Page({
  data: {
    userInfo: {
      nickName: '点击登录',
      avatarUrl: '/static/images/my.png'
    },
    userApproveInfo:{
      contactName:'',
      contactTel:'',
      contactAddress:'',
      userType:0,
      companyName:'',
      companyLogo:'',
      adminUsername:'',
      herbInfoList:[],
    },
    hasLogin: false,
    username: '',
    password: '',
    confirmPassword: '',
    mobile: '',
    code: '',

    contactName:'',
    contactTel:'',
    contactAddress:'',
    userTypes:[
      {value: '0', name: '个人经营户认证' , checked:true},
      {value: '1', name: '药材厂家'},
      {value: '2', name: '药材经销商'},
    ],
    userType:'0',
    herbList:[],
    companyName:'',
    logoUrls: [],
    files: [],
    qualificationUrls: [],
    qualificationFiles: []
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成
    this.getQualificationsDetail();
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
    //获取用户的登录信息
    if (app.globalData.hasLogin) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        userInfo: userInfo,
        hasLogin: true
      });
    }
  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  getQualificationsDetail(){
    wx.showLoading({
      title: '加载中',
    });
    setTimeout(function() {
      wx.hideLoading()
    }, 2000);
    
    let that = this;
    util.request(api.QualificationsDetail, {
      isAuth:1
    }).then(function(res) {
      if (res.errno === 0) {
        let userApproveInfo = res.data.userApproveInfo;
        let userType = userApproveInfo.userType+'';
        that.setData({
          userApproveInfo: userApproveInfo,
          userType:userType
        });
        if(userApproveInfo.contactName){
          that.setData({
            contactName: userApproveInfo.contactName
          });
        }
        if(userApproveInfo.contactTel){
          that.setData({
            contactTel: userApproveInfo.contactTel
          });
        }
        if(userApproveInfo.contactAddress){
          that.setData({
            contactAddress: userApproveInfo.contactAddress
          });
        }
        if(userType){
          that.onUserTypeSelect(userType);
        }
        if(userType == '0'){
          let herbInfoList = that.data.userApproveInfo.herbInfoList;
          // console.log(herbInfoList)
          if(herbInfoList && herbInfoList.length>0){
            that.setData({
              herbList: herbInfoList.map((item)=>{
                item.id = item.herbId;
                item.name=item.herbName;
                return item;
              })
            });
          }
        }else{
          if(userApproveInfo.companyName){
            that.setData({
              companyName: userApproveInfo.companyName
            });
          }
          if(userApproveInfo.adminUsername){
            that.setData({
              username: userApproveInfo.adminUsername
            });
          }

          let companyLogoStr = that.data.userApproveInfo.companyLogo;
          if(companyLogoStr!=null && companyLogoStr!=''){
            that.setData({
              logoUrls: companyLogoStr.split(','),
              files: companyLogoStr.split(',')
            });
          }
        }
        let certificatesImageStr = that.data.userApproveInfo.certificatesImage;
        if(certificatesImageStr!=null && certificatesImageStr!=''){
          that.setData({
            qualificationUrls: certificatesImageStr.split(','),
            qualificationFiles: certificatesImageStr.split(',')
          });
        }
      }
      wx.hideLoading();
    });
  },
  sendCode: function () {
    let that = this;

    if (this.data.mobile.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '手机号不能为空',
        showCancel: false
      });
      return false;
    }

    wx.request({
      url: api.AuthRegisterCaptcha,
      data: {
        mobile: that.data.mobile
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.errno == 0) {
          wx.showModal({
            title: '发送成功',
            content: '验证码已发送',
            showCancel: false
          });
        } else {
          wx.showModal({
            title: '错误信息',
            content: res.data.errmsg,
            showCancel: false
          });
        }
      }
    });
  },
  requestApplyAuth: function (wxCode) {
    let that = this;
    wx.request({
      url: api.AuthApplyAuth,
      data: {
        username: that.data.username,
        password: that.data.password,
        mobile: that.data.mobile,
        code: that.data.code,
        contactName: that.data.contactName,
        contactTel: that.data.contactTel,
        contactAddress:that.data.contactAddress,
        userType:that.data.userType,
        companyName:that.data.companyName,
        logoUrls: that.data.logoUrls,
        herbList:that.data.herbList.map((t)=> t.id),
        // herbList:that.data.herbList,
        qualificationUrls: that.data.qualificationUrls,
        wxCode: wxCode
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.errno == 0) {
          app.globalData.hasLogin = true;
          // wx.setStorageSync('userInfo', res.data.data.userInfo);
          wx.switchTab({
            url: '/pages/ucenter/index/index'
          });
          wx.navigateTo({
            url: "/pages/ucenter/qualifications/qualifications?status=1"
          });
        } else {
          wx.showModal({
            title: '错误信息',
            content: res.data.errmsg,
            showCancel: false
          });
        }
      }
    });
  },
  onUserTypeChange: function (e) {
    this.onUserTypeSelect(e.detail.value);
  },
  onUserTypeSelect:function(userType){
    const userTypes = this.data.userTypes
    for (let i = 0, len = userTypes.length; i < len; ++i) {
      userTypes[i].checked = userTypes[i].value === userType
    }
    this.setData({
      userTypes,
      userType:userType
    })
  },
  //添加herb
  addHerb:function(){
    let that = this;
    if (app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/herb/herb?herbListStr="+JSON.stringify(that.data.herbList)
      });
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  startAuthCheck:function(callback){
    if (app.globalData.hasLogin) {
      util.request(api.CouuntTargetStatus, {
        status: 0
      }).then(function(res) {
        if (res.errno === 0) {
          if(res.data > 0){
            wx.showModal({
              title: '错误信息',
              content: '存在未审核的认证信息',
              showCancel: false
            });
            return false;
          }else{
            callback();
          }
        }
      })
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    };
  },
  startAuth: function () {
    var that = this;

    if (this.data.contactName.length == 0 
      || this.data.contactTel.length == 0
      || this.data.contactAddress.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '联系人、电话、地址不能为空',
        showCancel: false
      });
      return false;
    }

    if('0' == this.data.userType){
      if(this.data.herbList.length == 0){
        wx.showModal({
          title: '错误信息',
          content: '请选择药品品类',
          showCancel: false
        });
        return false;
      }
    }
    else if( ['1','2'].includes(this.data.userType)){
      if (this.data.password.length < 6 || this.data.username.length < 6) {
        wx.showModal({
          title: '错误信息',
          content: '登录账号和密码不得少于6位',
          showCancel: false
        });
        return false;
      }

      if (this.data.password != this.data.confirmPassword) {
        wx.showModal({
          title: '错误信息',
          content: '确认密码不一致',
          showCancel: false
        });
        return false;
      }
    }
    if (this.data.qualificationUrls.length == 0) {
      wx.showModal({
        title: '错误信息',
        content: '请选上传资质图片',
        showCancel: false
      });
      return false;
    }

    that.requestApplyAuth('')
    // wx.login({
    //   success: function (res) {
    //     if (!res.code) {
    //       wx.showModal({
    //         title: '错误信息',
    //         content: '商户认证失败',
    //         showCancel: false
    //       });
    //     }
    //   }
    // });
  },
  bindUsernameInput: function (e) {

    this.setData({
      username: e.detail.value
    });
  },
  bindPasswordInput: function (e) {

    this.setData({
      password: e.detail.value
    });
  },
  bindConfirmPasswordInput: function (e) {

    this.setData({
      confirmPassword: e.detail.value
    });
  },
  bindMobileInput: function (e) {

    this.setData({
      mobile: e.detail.value
    });
  },
  bindCodeInput: function (e) {

    this.setData({
      code: e.detail.value
    });
  },
  bindContactNameInput: function (e) {
    this.setData({
      contactName: e.detail.value
    });
  },
  bindContactTelInput: function (e) {
    this.setData({
      contactTel: e.detail.value
    });
  },
  bindContactAddressInput: function (e) {
    this.setData({
      contactAddress: e.detail.value
    });
  },
  bindCompanyNameInput: function (e) {
    this.setData({
      companyName: e.detail.value
    });
  },
  clearInput: function (e) {
    switch (e.currentTarget.id) {
      case 'clear-username':
        this.setData({
          username: ''
        });
        break;
      case 'clear-password':
        this.setData({
          password: ''
        });
        break;
      case 'clear-confirm-password':
        this.setData({
          confirmPassword: ''
        });
        break;
      case 'clear-mobile':
        this.setData({
          mobile: ''
        });
        break;
      case 'clear-code':
        this.setData({
          code: ''
        });
        break;
      case 'clear-contact_name':
        this.setData({
          contactName: ''
        });
        break;
      case 'clear-contact_tel':
        this.setData({
          contactTel: ''
        });
        break;
      case 'clear-contact_address':
        this.setData({
          contactAddress: ''
        });
        break;
      case 'clear-company_name':
        this.setData({
          companyName: ''
        });
        break;
    }
  },
  chooseImage: function(e) {
    if (this.data.files.length >= 1) {
      util.showErrorToast('只能上传五张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        that.upload(res);
      }
    })
  },
  upload: function(res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: res.tempFilePaths[0],
      name: 'file',
      success: function(res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.url
          that.data.logoUrls.push(url)
          that.setData({
            logoUrls: that.data.logoUrls
          })
        }
      },
      fail: function(e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  //资质上传逻辑
  qualificationChooseImage: function(e) {
    if (this.data.qualificationFiles.length >= 5) {
      util.showErrorToast('只能上传五张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          qualificationFiles: that.data.qualificationFiles.concat(res.tempFilePaths)
        });
        that.qualificationsUpload(res);
      }
    })
  },
  qualificationsUpload: function(res) {
    var that = this;
    const uploadTask = wx.uploadFile({
      url: api.StorageUpload,
      filePath: res.tempFilePaths[0],
      name: 'file',
      success: function(res) {
        var _res = JSON.parse(res.data);
        if (_res.errno === 0) {
          var url = _res.data.url
          that.data.qualificationUrls.push(url)
          that.setData({
            qualificationUrls: that.data.qualificationUrls
          })
        }
      },
      fail: function(e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })

    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })

  },
  qualificationsPreviewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.qualificationFiles // 需要预览的图片http链接列表
    })
  },
})